<template>
  <a-drawer
    v-bind="$attrs"
    :body-style="{ paddingBottom: '80px' }"
    :mask-closable="false"
    :destroy-on-close="true"
    @after-visible-change="onAfterVisibleChange"
    @close="onClose"
  >
    <a-spin :spinning="props.loading">
      <a-form layout="vertical">
        <a-form-item label="名称" v-bind="editFormValidateInfos.name">
          <a-input v-model:value="modelRef.name" placeholder="请输入广告名称" />
        </a-form-item>
        <a-form-item label="广告类型" v-bind="editFormValidateInfos.imgType">
          <a-select
            v-model:value="modelRef.imgType"
            placeholder="请选择广告类型"
            :options="selectOptions.imgType"
            :field-names="{ label: 'value', value: 'type' }"
          ></a-select>
        </a-form-item>
        <a-form-item label="图片" v-bind="editFormValidateInfos.img">
          <a-upload
            v-model:file-list="uploadState.fileList"
            list-type="picture-card"
            :custom-request="handleCustomRequest"
            :before-upload="handleBeforeUpload"
            :max-count="1"
            @preview="handlePreview"
            @remove="handleRemove"
            @change="handleChange"
          >
            <div v-if="uploadState.fileList.length < 1" alt="avatar">
              <PlusOutlined />
              <div class="ant-upload-text">点击上传图片</div>
            </div>
          </a-upload>
          <a-modal
            :visible="uploadState.previewVisible"
            :title="uploadState.previewTitle"
            :footer="null"
            @cancel="handleCancel"
          >
            <img alt="example" style="width: 100%" :src="uploadState.previewImage" />
          </a-modal>
          <a-alert message="请上传JPG/PNG格式、2MB以内的图片" type="info" show-icon />
        </a-form-item>
        <a-form-item label="图片高级处理指令" v-bind="editFormValidateInfos.fileProcess">
          <a-input v-model:value="modelRef.fileProcess" placeholder="如有需要请输入高级图片处理指令" />
        </a-form-item>
        <a-form-item label="跳转类型" v-bind="editFormValidateInfos.jump">
          <a-select
            v-model:value="modelRef.jump"
            placeholder="请选择跳转类型"
            :options="selectOptions.jump"
            :field-names="{ label: 'value', value: 'key' }"
          ></a-select>
        </a-form-item>
        <a-form-item v-if="modelRef.jump != 1" label="跳转链接" v-bind="editFormValidateInfos.jumpUrl">
          <a-input v-model:value="modelRef.jumpUrl" placeholder="请输入跳转链接" />
        </a-form-item>
        <a-form-item label="排序" v-bind="editFormValidateInfos.sort">
          <a-input-number v-model:value="modelRef.sort" :min="0" placeholder="请输入排序" />
        </a-form-item>
        <a-form-item label="生效时段" v-bind="editFormValidateInfos.timeRange">
          <a-range-picker v-model:value="modelRef.timeRange" show-time />
        </a-form-item>
        <a-form-item label="状态" v-bind="editFormValidateInfos.enable">
          <a-switch v-model:checked="modelRef.enable" />
        </a-form-item>
        <a-form-item label="备注" v-bind="editFormValidateInfos.description">
          <a-textarea v-model:value="modelRef.description" :rows="4" placeholder="请输入广告描述信息" />
        </a-form-item>
      </a-form>
    </a-spin>
    <template #footer>
      <a-space>
        <a-button type="primary" @click.prevent="onSubmit">确定</a-button>
        <a-button @click="onClose">取消</a-button>
      </a-space>
    </template>
  </a-drawer>
</template>

<script lang="ts" setup>
import { reactive, ref, onBeforeMount, onMounted, onBeforeUnmount, onUnmounted, inject, toRefs } from 'vue'
import { PlusOutlined } from '@ant-design/icons-vue'
import { Form } from 'ant-design-vue'
import type { Rule } from 'ant-design-vue/es/form'
import { adModel } from '../model'
import { deepClone } from '@/utils/object'
import useUpload from '@/hooks/upload'
import { provideSelectOptions } from '../model'
import dayjs from 'dayjs'
import { isOverLength, isURL } from '@/utils/validate'

const props = defineProps({
  loading: {
    type: Boolean,
    default: false,
  },
  current: {
    type: Object,
    default: () => {
      return deepClone(adModel)
    },
  },
})

const onAfterVisibleChange = (visible) => {
  let _ad
  if (visible && props.current && props.current.id) {
    _ad = deepClone(props.current)
    uploadState.fileList[0] = {
      thumbUrl: _ad.imgUrl,
      url: _ad.imgUrl,
      name: _ad.img,
    }
    _ad.jump = selectOptions.jump.filter((item) => item.value == _ad.jump)[0].key
    _ad.timeRange = [dayjs(_ad.beginTime), dayjs(_ad.endTime)]
  } else {
    _ad = deepClone(adModel)
    uploadState.fileList = []
  }

  // form.data = _ad
  // console.log(form.data)

  modelRef.value = _ad

  if (props.loading) {
    emits('update:loading', false)
  }
}

const emits = defineEmits(['submit', 'update:visible', 'update:loading'])

let modelRef = ref(deepClone(adModel))
const rulesRef = reactive({
  name: [
    {
      required: true,
      message: '请输入广告名称',
    },
    {
      validator: async (_rule: Rule, value: string) => {
        if (isOverLength(value) > 50) {
          return Promise.reject('名称最大不能超过50个字符(中文算2字符)')
        } else {
          return Promise.resolve()
        }
      },
      trigger: 'change',
    },
  ],
  imgType: [
    {
      required: true,
      message: '请选择广告类型',
    },
  ],
  img: [
    {
      required: true,
      message: '请上传广告图片',
    },
  ],
  jump: [
    {
      required: true,
      message: '请选择跳转类型',
    },
  ],
  jumpUrl: [
    {
      validator: async (_rule: Rule, value: string) => {
        if (!value) return Promise.resolve()
        if (!isURL(value)) {
          return Promise.reject('请输入正确的链接地址！跳转链接必须包含http://或https://！')
        } else if (isOverLength(value) > 255) {
          return Promise.reject('跳转链接最大不能超过255个字符(中文算2字符)')
        } else {
          return Promise.resolve()
        }
      },
      trigger: 'change',
    },
  ],
  timeRange: [
    {
      required: true,
      message: '请选择生效时段',
    },
  ],
})

const handleChange = (info) => {
  if (info.file.status === 'done') {
    console.log(uploadState.fullName, ' done')
    modelRef.value.img = uploadState.key
    if (info.file.type === 'image/jpeg') {
      uploadState.fileProcess = 'image/quality,Q_70/interlace,1'
    } else if (info.file.type === 'image/png') {
      uploadState.fileProcess = ' image/quality,Q_70format,jpg/interlace,1'
    }
    modelRef.value.fileProcess = uploadState.fileProcess
  }
}

const handleRemove = (file) => {
  uploadState.key = ''
  uploadState.fullName = ''
  uploadState.fileProcess = ''
  modelRef.value.fileProcess = uploadState.fileProcess
}

const {
  uploadState,
  handlePreview,
  handleCancel,
  // handleChange,
  handleBeforeUpload,
  // handleRemove,
  handleCustomRequest,
  handleReset,
} = useUpload('ads')

const {
  resetFields: editFormResetFields,
  validate: editFormValidate,
  validateInfos: editFormValidateInfos,
} = Form.useForm(modelRef, rulesRef, {
  onValidate: (...args) => console.log(...args),
})

const selectOptions = inject(provideSelectOptions, []) as any

const onClose = () => {
  editFormResetFields()
  emits('update:visible', false)
}

const onSubmit = () => {
  // modelRef.value.img = uploadState.key
  editFormValidate()
    // .then(() => handleUpload())
    // .then(({ key }) => {
    //   form.data.img = key
    //   emits("submit", form.data)
    // })
    .then(() => {
      // form.data.img = uploadState.key
      // emits('submit', form.data)
      // modelRef.value.img = uploadState.key
      emits('submit', modelRef.value)
      console.log(modelRef.value)
      editFormResetFields()
      handleReset()
    })
    .catch((err) => {
      console.log('error', err)
    })
}
</script>
